﻿using System;
using System.Web.UI;
using System.Collections.Generic;
using Microsoft.SharePoint;
using System.Xml;
using System.Web;
using ServBus.ListForm2010.Utility;
using FluentRibbon.Libraries;
using FluentRibbon.Definitions;
using FluentRibbon;
using Microsoft.SharePoint.WebControls;
using FluentRibbon.Definitions.Controls;

namespace ServBus.ListForm2010.InfoBusFormWebPart
{
    public partial class InfoBusFormWebPartUserControl : UserControl
    {

        #region Parameters

        public static bool urlMode = true;
        public static string webpartMode = string.Empty;//"NEW";
        public static string siteName = string.Empty;//
        public static string webName = "";//"Test";
        public static string listId = "";//"test";
        public static string contentTypeId = "";
        public static string listName = "";//"test";
        public static string itemId = "";//string.Empty;

        public InfoBusFormWebPart webpart { get; set; }
        XmlNamespaceManager xNameSpace;

        static string pulishUrl = string.Empty;
        #endregion

        #region Page Method
        protected void Page_Load(object sender, EventArgs e)
        {

            try
            {
                SPRibbon ribbon = SPRibbon.GetCurrent(this.Page);
                if (ribbon != null)
                {
                    ribbon.TrimById("Ribbon.WebPartPage");
                }

                DecodeUrl();
                bool parameterStatus = true;
                #region Set Parameters
                    if (!string.IsNullOrEmpty(getWebpartMode()))
                    {
                        webpartMode = getWebpartMode().ToUpper();
                    }
                    else
                    {
                        parameterStatus = false;
                    }

                    siteName = SPContext.Current.Site.Url;

                    webName = SPContext.Current.Web.Name;

                    if (!string.IsNullOrEmpty(Request("listId")))
                    {
                        listId = Convert.ToString(Request("listId"));
                    }
                    else
                    {
                        parameterStatus = false;
                    }

                    if (!string.IsNullOrEmpty(Request("ID")))
                    {
                        itemId = Convert.ToString(Request("ID"));
                    }
                    else if (!string.IsNullOrEmpty(Request("itemId")))
                    {
                        itemId = Convert.ToString(Request("itemId"));
                    }
                    else if (!string.IsNullOrEmpty(Request("ctypeId")))
                    {
                        contentTypeId = Convert.ToString(Request("ctypeId"));
                    }
                    else
                    {
                        if (!webpartMode.Equals("NEW"))
                        {
                            parameterStatus = false;
                        }
                    }
                

                #endregion

                if (!Page.IsPostBack)
                {
                    if (parameterStatus)
                    {
                        switch (webpartMode)
                        {
                            case "NEW":
                                GenerateNewForm();
                                break;
                            case "DISPLAY":
                                GenerateDisplayForm();
                                break;
                            case "EDIT":
                                GenerateEditForm();
                                break;
                            default:
                                break;
                        }
                    }
                    else
                    {
                        exView.Visible = true;
                        exView.Text = "Parameters missed, please check!";
                    }
                }
            }
            catch (Exception ex)
            {
                //xDocView.Visible = false;
                exView.Visible = true;
                exView.Text = ex.ToString();
            }
        }

        #endregion

        #region Private Method

        private void GenerateDisplayForm()
        {
            String currurl = HttpUtility.UrlDecode(HttpContext.Current.Request.RawUrl.ToLower());
            string editUrl = currurl.Replace("display_lb.aspx", "edit_lb.aspx");
            #region add ribbon buttons
            var tabDefinition = new TabDefinition()
            {

                Id = "EditRibbon",
                Title = "Edit",
                Groups = new GroupDefinition[]
                {
                    new GroupDefinition()
                    {
                        Id = "manageGroup",
                        //Title = Resource.GetString("RibbonGroup_Submit"),
                        Title = "Manage",
                        Template = GroupTemplateLibrary.SimpleTemplate,
                        Controls = new ControlDefinition[]
                        {
                            new ButtonDefinition()
                            {
                                Id = "EditButton",
                                //Title = Resource.GetString("Btn_Save"),
                                Title = "Edit Item",
                                CommandJavaScript = "window.location =\""+editUrl+"\"",
                                //Image = ImageLibrary.GetStandardImage(8, 13,_currentlcid),
                                Image = new ImageDefinition()
                                { 
                                    Url32 = "/_layouts/InfoBus2010/Images/Edit32.png"
                                }
                            },
                            new ButtonDefinition()
                            {
                                Id = "DeleteButton",
                                //Title = Resource.GetString("Btn_Save"),
                                Title = "Delete Item",
                                CommandJavaScript = "deleteFormPart();",
                                //Image = ImageLibrary.GetStandardImage(8, 13,_currentlcid),
                                Image = new ImageDefinition()
                                { 
                                    Url32 = "/_layouts/InfoBus2010/Images/Delete32.png"
                                }
                            }                                 
                        }
                    },
                    new GroupDefinition()
                    {
                        Id = "closeGroup",
                        //Title = Resource.GetString("RibbonGroup_Submit"),
                        Title = "Close",
                        Template = GroupTemplateLibrary.SimpleTemplate,
                        Controls = new ControlDefinition[]
                        {                            
                            new ButtonDefinition()
                            {
                                Id = "CloseButton",
                                //Title = Resource.GetString("Btn_Close"),
                                Title ="Close",
                                CommandJavaScript = "window.frameElement.commitPopup('Operation Successful');",
                                //Image = ImageLibrary.GetStandardImage(9, 14,_currentlcid)
                                Image = new ImageDefinition()
                                { 
                                    Url32 = "/_layouts/InfoBus2010/Images/Close32.png"
                                }
                            }                                        
                        }
                    }
                }
            };



            RibbonController.Current.AddRibbonTabToPage(tabDefinition, this.Page, true);

            #endregion
            container.Attributes.Add("src", siteName + Constants.SERVICE_PAGE_INNER + "?wpMode=disp&itemId=" + itemId + "&listId=" + listId+"&ctype="+contentTypeId);
        }

        private void GenerateNewForm()
        {
            #region add ribbon buttons
            var tabDefinition = new TabDefinition()
            {

                Id = "EditRibbon",
                Title = "Edit",
                Groups = new GroupDefinition[]
                {
                    new GroupDefinition()
                    {
                        Id = "commitGroup",
                        //Title = Resource.GetString("RibbonGroup_Submit"),
                        Title = "Commit",
                        Template = GroupTemplateLibrary.SimpleTemplate,
                        Controls = new ControlDefinition[]
                        {
                            new ButtonDefinition()
                            {
                                Id = "SaveButton",
                                //Title = Resource.GetString("Btn_Save"),
                                Title = "Save",
                                CommandJavaScript = "saveFormPart();",
                                //Image = ImageLibrary.GetStandardImage(8, 13,_currentlcid),
                                Image = new ImageDefinition()
                                { 
                                    Url32 = "/_layouts/InfoBus2010/Images/Save32.png"
                                }
                            },
                            new ButtonDefinition()
                            {
                                Id = "CloseButton",
                                //Title = Resource.GetString("Btn_Close"),
                                Title ="Close",
                                CommandJavaScript = "window.frameElement.commitPopup('Operation Successful!');",
                                //Image = ImageLibrary.GetStandardImage(9, 14,_currentlcid)
                                Image = new ImageDefinition()
                                { 
                                    Url32 = "/_layouts/InfoBus2010/Images/Close32.png"
                                }
                            }                                        
                        }
                    }
                    
                }
            };



            RibbonController.Current.AddRibbonTabToPage(tabDefinition, this.Page, true);

            #endregion
            //Create the web form of the template xml document with the publish url.
            container.Attributes.Add("src", siteName + Constants.SERVICE_PAGE_INNER + "?wpMode=new&listId=" + listId + "&ctype=" + contentTypeId);
        }

        private void GenerateEditForm()
        {
            #region add ribbon buttons
            var tabDefinition = new TabDefinition()
            {

                Id = "EditRibbon",
                Title = "Edit",
                Groups = new GroupDefinition[]
                {
                    new GroupDefinition()
                    {
                        Id = "commitGroup",
                        //Title = Resource.GetString("RibbonGroup_Submit"),
                        Title = "Commit",
                        Template = GroupTemplateLibrary.SimpleTemplate,
                        Controls = new ControlDefinition[]
                        {
                            new ButtonDefinition()
                            {
                                Id = "SaveButton",
                                //Title = Resource.GetString("Btn_Save"),
                                Title = "Save",
                                CommandJavaScript = "saveFormPart();",
                                //Image = ImageLibrary.GetStandardImage(8, 13,_currentlcid),
                                Image = new ImageDefinition()
                                { 
                                    Url32 = "/_layouts/InfoBus2010/Images/Save32.png"
                                }
                            },
                            new ButtonDefinition()
                            {
                                Id = "CloseButton",
                                //Title = Resource.GetString("Btn_Close"),
                                Title ="Close",
                                CommandJavaScript = "window.frameElement.commitPopup('Operation Successful');",
                                //Image = ImageLibrary.GetStandardImage(9, 14,_currentlcid)
                                Image = new ImageDefinition()
                                { 
                                    Url32 = "/_layouts/InfoBus2010/Images/Close32.png"
                                }
                            }                                        
                        }
                    },
                    new GroupDefinition()
                    {
                        Id = "actionsGroup",
                        //Title = Resource.GetString("RibbonGroup_Submit"),
                        Title = "Actions",
                        Template = GroupTemplateLibrary.SimpleTemplate,
                        Controls = new ControlDefinition[]
                        {
                            new ButtonDefinition()
                            {
                                Id = "DeleteButton",
                                //Title = Resource.GetString("Btn_Save"),
                                Title = "Delete Item",
                                CommandJavaScript = "deleteFormPart();",
                                //Image = ImageLibrary.GetStandardImage(8, 13,_currentlcid),
                                Image = new ImageDefinition()
                                { 
                                    Url32 = "/_layouts/InfoBus2010/Images/Delete32.png"
                                }
                            }                                 
                        }
                    }
                }
            };



            RibbonController.Current.AddRibbonTabToPage(tabDefinition, this.Page, true);

            #endregion
            container.Attributes.Add("src", siteName + Constants.SERVICE_PAGE_INNER + "?wpMode=edit&itemId=" + itemId + "&listId=" + listId + "&ctype=" + contentTypeId);
        }

        private string getWebpartMode()
        {
            String currurl = HttpUtility.UrlDecode(HttpContext.Current.Request.RawUrl.ToUpper());
            currurl = currurl.Split('?')[0];
            if (currurl.EndsWith("NEW_LB.ASPX"))
            {
                return "NEW";
            }
            else if (currurl.EndsWith("DISPLAY_LB.ASPX"))
            {
                return "DISPLAY";
            }
            else if (currurl.EndsWith("EDIT_LB.ASPX"))
            {
                return "EDIT";
            }
            return null;
        }

        private Dictionary<string, string> urlParamDic = new Dictionary<string, string>();
        private void DecodeUrl()
        {
            String currurl = HttpUtility.UrlDecode(HttpContext.Current.Request.RawUrl.ToUpper());
            String querystring = null;

            // Check to make sure some query string variables
            // exist and if not add some and redirect.
            int iqs = currurl.IndexOf('?');
            if (iqs >= 0)
            {
                querystring = (iqs < currurl.Length - 1) ? currurl.Substring(iqs + 1) : String.Empty;
            }

            // Parse the query string variables into a NameValueCollection.
            System.Collections.Specialized.NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);

            // Iterate through the collection.
            foreach (String s in qscoll.AllKeys)
            {
                urlParamDic.Add(s, qscoll[s]);
            }
        }

        private string Request(string param)
        {
            string returnValue = string.Empty;

            if (urlParamDic.ContainsKey(param.ToUpper()))
            {
                returnValue = urlParamDic[param.ToUpper()];
            }
            return returnValue;
        }
        #endregion
    }
}
